//
//  QXNetWorkTool.m
//  CommunityNannyO2O
//
//  Created by Apple on 15/7/18.
//  Copyright (c) 2015年 Apple. All rights reserved.
//

#import "QXNetWorkTool.h"
#import "SBJSON.h"
#import <CommonCrypto/CommonCryptor.h>
#import "AppConfig.h"
#import "NSString+AESCrypt.h"
#import "NSData+AESCrypt.h"
#import "GTMBase64.h"
static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
#define     LocalStr_None           @""
@implementation QXNetWorkTool
//@synthesize QXNetWorkDelegate;
-(void)GetDataFromServerWithPostMethodandInterfaceName:(NSString *)InterfaceName andParameter:(NSArray *)parameter tag:(NSInteger *)tag
{
    SBJSON *sbJson = [[SBJSON alloc]init];
    NSDictionary *dic = @{@"type":InterfaceName,
                          @"data":parameter};
//    NSArray *array = [[NSArray alloc]initWithObjects:dic, nil];
    NSString *PostString = [sbJson stringWithObject:dic];
    
    NSString *postDcodeString2 = [self AES128Encrypt:PostString];
    QXNSUrlConnection *qxUrlConnection = [[QXNSUrlConnection alloc]init];
   // NSLog(@"%@",self);
    
    qxUrlConnection.tag = tag;
    
    qxUrlConnection.QXUrlDelegate = self;
   // NSLog(@"%@",qxUrlConnection.QXUrlDelegate);
    [qxUrlConnection sendAPIWithUrl:[NSURL URLWithString:APIHOST] AndMethod:@"POST" AndDataBody:postDcodeString2];
    
    
}
- (void)GetSuccessResponse:(id)Response andTag:(int)tag ;
{
    if ([self.QXNetWorkDelegate respondsToSelector:@selector(GetSuccessResponse:andTag:)])
    {
        [self.QXNetWorkDelegate GetSuccessResponse:Response andTag:tag];
    }
}

-(void)GetFailResponse:(id)Response andTag:(int)tag{


    if ([self.QXNetWorkDelegate respondsToSelector:@selector(GetFailResponse:andTag:)]) {
        [self.QXNetWorkDelegate GetFailResponse:Response andTag:tag];

    }
}

- (void)GetSuccessMessage:(id)message andTag:(int)tag
{
    if ([self.QXNetWorkDelegate respondsToSelector:@selector(GetSuccessMessage:andTag:)]) {
        [self.QXNetWorkDelegate GetSuccessMessage:message andTag:tag];
    }
}
  
- (NSString *)AES256ParmEncryptWithKey:(NSString *)key andDataString:(NSString *)dataString   //加密
{
    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    char keyPtr[kCCKeySizeAES128+1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    char ivPtr[kCCBlockSizeAES128+1];
    memset(ivPtr, 0, sizeof(ivPtr));
    [APPIV getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [data length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void  *buffer = malloc(bufferSize);
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr, kCCBlockSizeAES128,
                                          ivPtr,
                                          [data bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        NSString *string = [[NSString alloc]initWithData:[NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted] encoding:NSASCIIStringEncoding];
        //NSLog(@"%@",[GTMBase64 stringByEncodingData:[NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted]]);
        return string ;
    }
    free(buffer);
    return nil;
}






-(NSString *)AES128Encrypt:(NSString *)plainText
{
    char keyPtr[kCCKeySizeAES128+1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [APPKEY getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    char ivPtr[kCCBlockSizeAES128+1];
    memset(ivPtr, 0, sizeof(ivPtr));
    [APPIV getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    
    NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [data length];
    
    int diff = kCCKeySizeAES128 - (dataLength % kCCKeySizeAES128);
    int newSize = 0;
    
    if(diff > 0)
    {
        newSize = (int)(dataLength + diff);
    }
    
//    char dataPtr[newSize];x

    char * dataPtr = malloc(newSize);
    
//    memcpy(dataPtr, "\0", newSize);
    
    memcpy(dataPtr, [data bytes], [data length]);
    for(int i = 0; i < diff; i++)
    {
        dataPtr[i + dataLength] = '\0';
    }
    
    size_t bufferSize = newSize + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    memset(buffer, 0, bufferSize);
    
    size_t numBytesCrypted = 0;
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmAES128,
                                          0x0000,               //No padding
                                          keyPtr,
                                          kCCKeySizeAES128,
                                          ivPtr,
                                          dataPtr,
//                                          sizeof(dataPtr),
                                          newSize,
                                          buffer,
                                          bufferSize,
                                          &numBytesCrypted);
    
    if (cryptStatus == kCCSuccess) {
        NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
       // NSLog(@"%@",[GTMBase64 stringByEncodingData:resultData]);
        return [GTMBase64 stringByEncodingData:resultData];
    }
    free(dataPtr);
    free(buffer);
    return nil;
}

-(NSString *)AES128Decrypt:(NSString *)encryptText
{
    char keyPtr[kCCKeySizeAES128 + 1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [APPKEY getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    char ivPtr[kCCBlockSizeAES128 + 1];
    memset(ivPtr, 0, sizeof(ivPtr));
    [APPKEY getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    
    NSData *data = [GTMBase64 decodeData:[encryptText dataUsingEncoding:NSUTF8StringEncoding]];
    NSUInteger dataLength = [data length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesCrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          kCCAlgorithmAES128,
                                          0x0000,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          ivPtr,
                                          [data bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesCrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
        return [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
    }
    free(buffer);
    return nil;
}











- (NSString *)AES128Operation:(CCOperation)operation key:(NSString *)key iv:(NSString *)iv andDataString:(NSString *)dataString
{//加密
    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    char keyPtr[kCCKeySizeAES128 + 1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    char ivPtr[kCCBlockSizeAES128 + 1];
    memset(ivPtr, 0, sizeof(ivPtr));
    [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [data length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesCrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(operation,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          ivPtr,
                                          [data bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesCrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *data2 =  [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
    }
    free(buffer);
    return nil;
}

//-(NSData*) encryptText:(NSString*)text {
//    CCCryptorStatus status = kCCSuccess;
//    NSData* result = [[text dataUsingEncoding:NSUTF8StringEncoding]
//                      dataEncryptedUsingAlgorithm:kCCAlgorithmAES128
//                      key:APPKEY
//                      initializationVector:APPIV
//                      options:(kCCOptionPKCS7Padding|kCCOptionECBMode)
//                      error:&status];
//    if (status != kCCSuccess) {
//        NSLog(@"加密失败");
//        return nil;
//    }
//    //    NSString *string = [[NSString alloc]initWithData:result encoding:NSUTF8StringEncoding];
//    NSString *string = [self newStringInBase64FromData:result];
//    NSString *string3= @"U2FsdGVkX18df+l6MdjAze1vvV6ZOBuROR4c2/Bpav4=";
//    
//    NSString *string2 = [self decryptText:[string3 dataUsingEncoding:NSUTF8StringEncoding]] ;
//    NSLog(@"%@",result);
//    return result;
//}
- (NSString *)newStringInBase64FromData:(NSData *)data            //追加64编码

{
    
    NSMutableString *dest = [[NSMutableString alloc] initWithString:@""];
    
    unsigned char * working = (unsigned char *)[data bytes];
    
    int srcLen = [data length];
    
    for (int i=0; i<srcLen; i += 3) {
        
        for (int nib=0; nib<4; nib++) {
            
            int byt = (nib == 0)?0:nib-1;
            
            int ix = (nib+1)*2;
            
            if (i+byt >= srcLen) break;
            
            unsigned char curr = ((working[i+byt] << (8-ix)) & 0x3F);
            
            if (i+nib < srcLen) curr |= ((working[i+nib] >> ix) & 0x3F);
            
            [dest appendFormat:@"%c", base64[curr]];
            
        }
        
    }
    
    return dest;
    
}

//-(NSString*) decryptText:(NSData*)data {
//    CCCryptorStatus status = kCCSuccess;
//    NSData* result = [data
//                      decryptedDataUsingAlgorithm:kCCAlgorithmAES128
//                      key:APPKEY
//                      initializationVector:APPIV
//                      options:(kCCOptionPKCS7Padding|kCCOptionECBMode)
//                      error:&status];
//    if (status != kCCSuccess) {
//        return nil;
//    }
//    return [[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding];
//}




-(NSString *)AES128Encrypt:(NSString *)plainText withKey:(NSString *)key
{
    
    
    
    char keyPtr[kCCKeySizeAES128+1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    
    char ivPtr[kCCBlockSizeAES128+1];
    memset(ivPtr, 0, sizeof(ivPtr));
    [APPIV getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    
    NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [data length];
    
    int diff = kCCKeySizeAES128 - (dataLength % kCCKeySizeAES128);
    unsigned long newSize = 0;
    
    if(diff > 0)
    {
        newSize = dataLength + diff;
        NSLog(@"diff is %d",diff);
    }
    
    char dataPtr[newSize];
    memcpy(dataPtr, [data bytes], [data length]);
    for(int i = 0; i < diff; i++)
    {
        dataPtr[i + dataLength] =0x0000;
    }
    
    size_t bufferSize = newSize + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    memset(buffer, 0, bufferSize);
    
    size_t numBytesCrypted = 0;
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmAES128,
                                          0x0000,
                                          [key UTF8String],
                                          kCCKeySizeAES128,
                                          [key UTF8String],
                                          dataPtr,
                                          sizeof(dataPtr),
                                          buffer,
                                          bufferSize,
                                          &numBytesCrypted);
    
    if (cryptStatus == kCCSuccess) {
        NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
        NSLog(@"%@",[GTMBase64 stringByEncodingData:resultData]);
        return [GTMBase64 stringByEncodingData:resultData];
    }
    free(buffer);
    return nil;
}



@end
